import 'package:enjoy_plus/main.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:go_router/go_router.dart';

import '../../utils/ToastUtil.dart';
import '../../utils/eventbus.dart';
import 'house_list_item.dart';

///房屋列表
class HousePage extends StatefulWidget {
  const HousePage({super.key});

  @override
  State<HousePage> createState() => _HousePageState();
}

class _HousePageState extends State<HousePage> {
  List houseList = [];

  // 发送网络请求
  void getHouseList() async {
    try {
      // 请求数据
      var res = await Http.getInstance().get('/room');
      if (res['code'] != 10000) return ToastUtil.showError('获取数据失败');
      // ToastUtil.showSuccess('获取数据成功');
      setState(() {
        houseList = res['data'];
      });
    } catch (e) {
      debugPrint('请求失败：$e');
      ToastUtil.showError('获取数据失败');
    }
  }

  @override
  void initState() {
    super.initState();
    getHouseList();
    eventBus.on<RefreshHouseList>().listen((event) {
      setState(() {
        houseList = [];
        getHouseList();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的房屋'),
      ),
      body: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          // 当houseList列表为空的时候展示空页面，否则才展示listview
          houseList.isEmpty
              ? Container(
                  alignment: Alignment.center,
                  child: const Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.hourglass_empty),
                      Text('暂无数据'),
                    ],
                  ),
                )
              : ListView.builder(
                  itemBuilder: (context, index) {
                    return HouseListItem(houseItem: houseList[index]);
                  },
                  itemCount: houseList.length),

          Positioned(
              child: Container(
            height: 60,
            margin: const EdgeInsets.only(bottom: 10),
            padding: const EdgeInsets.only(left: 10, right: 10),
            width: MediaQuery.of(context).size.width,
            child: ElevatedButton(
              onPressed: () {
                context.push('/location_list');
              },
              child: const Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.add),
                  Text('添加房屋'),
                ],
              ),
            ),
          )),
        ],
      ),
    );
  }
}
